﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ReactiveXLearning
{
    public partial class frmNavigate : Form
    {
        public frmNavigate()
        {
            InitializeComponent();
            Load += FrmNavigate_Load;
        }

        private void FrmNavigate_Load(object sender, EventArgs evt)
        {
            lb_navigate.DrawItem += Lb_navigate_DrawItem;
            lb_navigate.DoubleClick += Lb_navigate_DoubleClick;

            #region 查找所有Base窗体

            var forms = Assembly.GetExecutingAssembly().GetTypes()
                .Where(x => x.IsSubclassOf(typeof(frmBase)))
                .ToDictionary(x => x.Name.Replace("frm", string.Empty));

            var rx_items = new List<RxNavigateItem>();

            foreach (var item in forms)
            {
                rx_items.Add(new RxNavigateItem { name = item.Key, form_type = item.Value });
            }

            lb_navigate.DataSource = rx_items;

            #endregion
        }

        private void Lb_navigate_DoubleClick(object sender, EventArgs e)
        {
            if (lb_navigate.SelectedItem == null || !(lb_navigate.SelectedItem is RxNavigateItem)) return;
            var item = lb_navigate.SelectedItem as RxNavigateItem;
            var form = Activator.CreateInstance(item.form_type) as Form;
            if (form != null) form.Show();
        }

        private void Lb_navigate_DrawItem(object sender, DrawItemEventArgs e)
        { 
            if (e.Index == -1)
                return;
            
            Font prefixFont = new Font(e.Font, FontStyle.Bold);

            RxNavigateItem navi = (RxNavigateItem)((ListBox)sender).Items[e.Index];

            Brush br = new SolidBrush(e.ForeColor);

            e.DrawBackground();
            Rectangle newBounds = new Rectangle(e.Bounds.Location, e.Bounds.Size);

            newBounds.X += 40;
            newBounds.Y += e.Bounds.Height / 2 - 9;
            
            e.Graphics.DrawString(navi.name, prefixFont, br, newBounds, StringFormat.GenericDefault);
            
            e.DrawFocusRectangle();
        }

        class RxNavigateItem
        {
            public string name { set; get; }

            public Type form_type { set; get; }
        }
    }
}
